package com.dd.lnetwork.provider

import android.app.Application
import android.content.Context

class ProviderManger private constructor(
    private var _deviceId: String,
    private var _token: String?,
    private var _cookies: HashSet<String>?
) {
    companion object {
        @Volatile
        var instance: ProviderManger? = null
        var hasInit: Boolean = false
        lateinit var context: Context
        fun getInstance(
            deviceId: String,
            token: String?,
            cookies: HashSet<String>
        ): ProviderManger {
            return if (!hasInit) {
                throw ProviderException("ProviderManger init first")
            } else {
                instance ?: synchronized(this) {
                    instance ?: ProviderManger(deviceId, token, cookies).apply { instance = this }
                }
            }
        }

        fun init(application: Application) {
            if (!hasInit) {
                context = application
                hasInit = true
            }
        }
    }

    /**
     * 获取 provider 实例
     *
     * @param cls
     * @param <T>
     * @return
    </T> */
    @Synchronized
    fun <T : IProvider> build(cls: Class<T>): T {
        return ProviderProxy.getProvider(cls, context, _deviceId, _token, _cookies)
    }

    /**
     * 注册 provider
     *
     * @param provider
     * @param providerImp
     * @param <T>
     * @param <K>
    </K></T> */
    fun <T : IProvider, K : T> addProvider(provider: Class<T>, providerImp: Class<K>) {
        ProviderProxy.addProvider(provider, providerImp)
    }
}